package org.game.module.activitybo;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.bean.ActivityEntryInfo;
import org.bean.ActivityInfo;
import org.cache.ActivityInfoCache;
import org.constant.ActivityConstant;
import org.constant.smallkey.ActivitySmallKey;
import org.error.GameErrorCode;
import org.game.constant.SessionConstent;
import org.game.db.bean.Player;
import org.game.db.bean.PlayerActivity;
import org.game.db.cache.PlayerActivityCache;
import org.game.db.vo.BaseActivity;
import org.game.db.vo.ServerActivityProxy;
import org.game.log.builder.LogDsp;
import org.game.log.dsp.GoodsDsp;
import org.game.manager.ActivityManager;
import org.game.manager.ItemManager;
import org.game.msgBuilder.ActivityMsgBuilder;
import org.game.protobuf.c2s.C2SActivityMsg.ReqActivitys;
import org.game.protobuf.c2s.C2SActivityMsg.SubmitActivity;
import org.game.protobuf.s2c.S2CActivityMsg.ActivityInfoMsg;
import org.game.protobuf.s2c.S2CActivityMsg.PushActivitys;
import org.game.protobuf.s2c.S2CActivityMsg.RespActivitys;
import org.game.protobuf.s2c.S2CActivityMsg.ResultSubmitActivity;
import org.game.protobuf.s2c.S2CShareMsg.ChangeType;
import org.game.protobuf.s2c.S2CShareMsg.RewardsMsg;
import org.game.util.ProtoUnit;
import org.utils.CommonUtil;
import org.utils.RemoteUtil;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sojoys.artifact.exception.AbstractLogicModelException;
import com.sojoys.artifact.factory.session.ISession;
import com.sojoys.artifact.tools.ToolError;
import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.util.ArrayUtil;

/**
 * @author : DengYing
 * @CreateDate : 2018年3月6日 下午2:41:47
 * @Description ：Please describe this document
 */
public class ActivityBOImpl implements ActivityBO {


	@Override
	public byte[] getAllActivity(ISession session, ReqActivitys msg) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		
		// 个人活动
		List<PlayerActivity> playerActivitys = player.getPlayerActivitysFkPlayerId();

		List<ActivityInfoMsg.Builder> playerActivityBuilders = ActivityMsgBuilder.createActivityInfoMsgs(player,ChangeType.DEFAULT,playerActivitys);
		
		
		// 全服活动
		List<ServerActivityProxy> serverActivitys = Lists.newArrayList();
		for (ActivityInfo activityInfo : ActivityInfoCache.getAllCache()) {
			if(activityInfo.getDataType()!=ActivityConstant.ACTIVITY_DATA_TYPE_SERVER){
				continue;
			}
			ServerActivityProxy serverActivity = new ServerActivityProxy(activityInfo);
			serverActivitys.add(serverActivity);
		}
		List<ActivityInfoMsg.Builder> serverActivityBuilders = ActivityMsgBuilder.createActivityInfoMsgs(player,ChangeType.DEFAULT,serverActivitys);
		
		
		
		RespActivitys.Builder respBuilder = RespActivitys.newBuilder();
		for (ActivityInfoMsg.Builder builder : playerActivityBuilders) {
			respBuilder.addActivitys(builder);
		}
		for (ActivityInfoMsg.Builder builder : serverActivityBuilders) {
			respBuilder.addActivitys(builder);
		}
		return ProtoUnit.toByte(respBuilder.build());
	}

	@Override
	public byte[] submit(ISession session, SubmitActivity msg) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		
		ActivityInfo activityInfo = ActivityInfoCache.getById(msg.getActivitId());
		
		BaseActivity baseActivity = null;
		if (activityInfo!=null) {
			switch (activityInfo.getDataType()) {
			case ActivityConstant.ACTIVITY_DATA_TYPE_PLAYER:
				baseActivity = PlayerActivityCache.me().getByActivityIdPlayerId(msg.getActivitId(), player.getId());
				break;
			case ActivityConstant.ACTIVITY_DATA_TYPE_SERVER:
				baseActivity = new ServerActivityProxy(activityInfo);
				break;
			}
		}
		ToolError.isAndTrue(GameErrorCode.NOT_FOND_ACTIVITY,"活动不存在", baseActivity == null || activityInfo==null || activityInfo.getStatus() == ActivityConstant.END);
		
		// 条目检查
		for (Integer activitEntryId : msg.getActivitEntryIdList()) {
			Map<Integer, Integer> entry = (Map<Integer, Integer>) baseActivity.getEntry(player.getId()).computeIfAbsent(activitEntryId, k -> new HashMap<>(2));
			ActivityEntryInfo activityEntryInfo = activityInfo.getEntrys().get(activitEntryId);
			
			ToolError.isAndTrue(GameErrorCode.NOT_FOND_ACTIVITY_ENTRY,"活动条目不存在", entry==null || activityEntryInfo==null);
			
			int status = MapUtils.getIntValue(entry, ActivitySmallKey.STATUS ,0 );
			ToolError.isAndTrue(GameErrorCode.ACTIVITY_ENTRY_STATUS_ERROR,"状态错误", status != ActivityConstant.ENTRY_STATUS_FINISH);
		}
		
		
		LogDsp logDsp = LogDsp.newBuilder(GoodsDsp.SUBMIT_ACTIVITY).addAttr("activitId", msg.getActivitId());
		Map<Integer, Integer> map = Maps.newHashMap();
		if (baseActivity instanceof PlayerActivity) {
			for (Integer activitEntryId : msg.getActivitEntryIdList()) {
				ActivityEntryInfo activityEntryInfo = activityInfo.getEntrys().get(activitEntryId);
				Map<Integer, Integer> entry = (Map<Integer, Integer>) baseActivity.getEntry(player.getId()).computeIfAbsent(activitEntryId, k -> new HashMap<>(2));
				entry.put(ActivitySmallKey.STATUS, ActivityConstant.ENTRY_STATUS_RECEIVE);
				
				logDsp.addAttr("entryId", activitEntryId);
				// 奖励累计
				CommonUtil.changeMap(map, activityEntryInfo.getReward());
			}
			PlayerActivity playerActivity = (PlayerActivity) baseActivity;
			playerActivity.update();
			
		}else if (baseActivity instanceof ServerActivityProxy) {
			
			// 同步提交远程
			RemoteUtil.socialSync().uploadActivityEntryStatus(msg.getActivitId(),msg.getActivitEntryIdList(), player.getId(), ActivityConstant.ENTRY_STATUS_RECEIVE);
			
			for (Integer activitEntryId : msg.getActivitEntryIdList()) {
				ActivityEntryInfo activityEntryInfo = activityInfo.getEntrys().get(activitEntryId);
				Map<Integer, Integer> statuMaps = (Map<Integer, Integer>) activityEntryInfo.getExtend().computeIfAbsent(ActivitySmallKey.SUBMIT_LOG, k -> Maps.newHashMap());
				statuMaps.put(player.getId(), ActivityConstant.ENTRY_STATUS_RECEIVE);
				
				logDsp.addAttr("entryId", activitEntryId);
				// 奖励累计
				CommonUtil.changeMap(map, activityEntryInfo.getReward());
			}
		}
		
		
//		for (Integer activitEntryId : msg.getActivitEntryIdList()) {
//			Map<Integer, Integer> entry = (Map<Integer, Integer>) baseActivity.getEntry(player.getId()).computeIfAbsent(activitEntryId, k -> new HashMap<>(2));
//			ActivityEntryInfo activityEntryInfo = activityInfo.getEntrys().get(activitEntryId);
//			
//			if (baseActivity instanceof PlayerActivity) {
//				PlayerActivity playerActivity = (PlayerActivity) baseActivity;
//				entry.put(ActivitySmallKey.STATUS, ActivityConstant.ENTRY_STATUS_RECEIVE);
//				playerActivity.update();
//			}else if (baseActivity instanceof ServerActivityProxy) {
//				// 同步提交远程
//				RemoteUtil.socialSync().uploadActivityEntryStatus(msg.getActivitId(), activitEntryId, player.getId(), ActivityConstant.ENTRY_STATUS_RECEIVE);
//				Map<Integer, Integer> statuMaps = (Map<Integer, Integer>) activityEntryInfo.getExtend().computeIfAbsent(ActivitySmallKey.SUBMIT_LOG, k -> Maps.newHashMap());
//				statuMaps.put(player.getId(), ActivityConstant.ENTRY_STATUS_RECEIVE);
//			}
//			logDsp.addAttr("entryId", activitEntryId);
//			
//			// 奖励累计
//			CommonUtil.changeMap(map, activityEntryInfo.getReward());
//		}
		
		
		
		
		List<RewardsMsg> rewards = ItemManager.unpackNotify(player,map,logDsp);
		
		// 推送活动更新
		ActivityInfoMsg.Builder activityInfoBuilder = ActivityMsgBuilder.createActivityInfoMsg(player,ChangeType.UPDATE, baseActivity);
		ActivityManager.me().notifyActivity(player,PushActivitys.newBuilder().addActivitys(activityInfoBuilder));
		
		// 返回数据封装
		ResultSubmitActivity.Builder resultBuilder = ResultSubmitActivity.newBuilder();
		resultBuilder.setActivityid(msg.getActivitId());
		resultBuilder.addAllActivitEntryId(msg.getActivitEntryIdList());
		resultBuilder.addAllRewards(rewards);
		return ProtoUnit.toByte(resultBuilder.build());
	}
}
